#!/usr/bin/env node

/**
 * 检查用户admin关联状态
 */

const AdminModel = require('../project/model/admin_model.js');
const UserModel = require('../project/model/user_model.js');

async function checkUserAdminStatus() {
    try {
        console.log('=== 检查用户admin关联状态 ===');
        
        const userId = 'oPOlNvkKFRjdTazLzUq6D2sHunp0'; // 微信openId
        
        console.log('检查用户ID:', userId);
        
        // 首先检查用户是否存在
        const user = await UserModel.getOne({
            _id: userId
        }, '_id,nickName,adminId');

        if (!user) {
            console.log('❌ 用户不存在');
            return {
                success: false,
                message: '用户不存在'
            };
        }

        console.log('✅ 用户存在:', user.nickName);

        // 查询所有admin记录
        const allAdmins = await AdminModel.getList({}, 'ADMIN_ID,ADMIN_NAME,linkedUserId,ADMIN_STATUS,isActive');
        
        console.log('\n所有admin记录:');
        allAdmins.forEach((admin, index) => {
            console.log(`${index + 1}. Admin ID: ${admin.ADMIN_ID}`);
            console.log(`   Admin Name: ${admin.ADMIN_NAME}`);
            console.log(`   Linked User ID: ${admin.linkedUserId || '未关联'}`);
            console.log(`   Admin Status: ${admin.ADMIN_STATUS}`);
            console.log(`   Is Active: ${admin.isActive}`);
            console.log(`   是否匹配当前用户: ${admin.linkedUserId === userId ? '✅ 是' : '❌ 否'}`);
            console.log('---');
        });
        
        // 查询当前用户关联的admin
        const userAdmin = await AdminModel.getOne({
            linkedUserId: userId,
            ADMIN_STATUS: 1,
            isActive: true
        }, 'ADMIN_ID,ADMIN_NAME,ADMIN_TYPE,linkedStoreIds,permissions,role');
        
        if (userAdmin) {
            console.log('\n✅ 用户已关联admin账号:');
            console.log('Admin ID:', userAdmin.ADMIN_ID);
            console.log('Admin Name:', userAdmin.ADMIN_NAME);
            console.log('Admin Type:', userAdmin.ADMIN_TYPE);
            console.log('Role:', userAdmin.role);
            console.log('Permissions:', userAdmin.permissions);
            console.log('Linked Store IDs:', userAdmin.linkedStoreIds);
        } else {
            console.log('\n❌ 用户未关联任何admin账号');
        }
        
        console.log('\n=== 检查完成 ===');
        
        return {
            success: true,
            hasAdmin: !!userAdmin,
            adminInfo: userAdmin,
            userInfo: user,
            allAdmins: allAdmins
        };
        
    } catch (error) {
        console.error('❌ 检查失败:', error);
        return {
            success: false,
            message: '检查失败: ' + error.message
        };
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    checkUserAdminStatus().then(result => {
        console.log('检查结果:', result);
        process.exit(result.success ? 0 : 1);
    }).catch(error => {
        console.error('脚本执行失败:', error);
        process.exit(1);
    });
}

module.exports = { checkUserAdminStatus };
